package edu.zut.cs.network.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import edu.zut.cs.network.base.BaseMainCase;

public class JdbcExample extends BaseMainCase {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	private static String sql;
	Connection conn = null;
	ResultSet rs = null;
	Statement st = null;
	static {

		InputStream is = JdbcExample.class.getResourceAsStream("/jdbc.properties");//读文件获取账户密码等信息
		Properties prop = new Properties();//新建一个空属性列表
		try {
			prop.load(is); //从输入流中读取属性列表（键和元素对）
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		driver = prop.getProperty("jdbc.driver");//用指定的键在此属性列表中搜索属性
		url = prop.getProperty("jdbc.url");
		username = prop.getProperty("jdbc.username");
		password = prop.getProperty("jdbc.password");
		sql = prop.getProperty("jdbc.sql");
		// 将JDBC驱动加载到JVM中
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		JdbcExample jdbcExample = new JdbcExample();
		jdbcExample.query();
	}

	public void query() throws SQLException, ClassNotFoundException {
		conn = DriverManager.getConnection(url, username, password);
		st = conn.createStatement();//创建一个 Statement 对象来将 SQL 语句发送到数据库。
		rs = st.executeQuery(sql);//执行给定的 SQL 语句，该语句返回单个 ResultSet 对象
		while (rs.next()) {
			logger.info(rs.getString(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3));
		}

		rs.close();
		st.close();
		conn.close();
	}
}
